package cn.itcast.shop.admin.admin.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.shop.admin.admin.domain.Admin;

/**
 * 
 * 管理员模块的Dao层
 * @author 10467
 *
 */
@Repository
@Transactional
public class AdminDao {
	@Autowired
	private SessionFactory sessionFactory;
	
	private Session getSession(){
		return sessionFactory.getCurrentSession();
	}
	/**
	 * 登陆方法
	 * @param username
	 * @param password
	 * @return
	 */
	public Admin login(String username, String password) {
		String hql = "from Admin where username=? and password=?";
		@SuppressWarnings("unchecked")
		List<Admin> list = getSession().createQuery(hql).setParameter(0, username).setParameter(1, password).list();
		if(list!=null && list.size()>0){
			return list.get(0);
		}else{
			return null;
		}
	}
	/**
	 * 查询管理员总数
	 * @return
	 */
	public int getAdminCount() {
		String hql = "select count(*) from Admin ";
		int count = ((Long)getSession().createQuery(hql).uniqueResult()).intValue();
		return count;
	}
	/**
	 * 查询所有管理员
	 * @param begin
	 * @param limit
	 * @return
	 */
	public List<Admin> findAllAdmin(int begin, int limit) {
		Query query = getSession().createQuery("from Admin order by uid desc ");
		query.setFirstResult(begin);
		query.setMaxResults(limit);
		@SuppressWarnings("unchecked")
		List<Admin> list = query.list();
		return list;
	}
	/**
	 * 删除管理员
	 * @param uid
	 */
	public void delete(Integer uid) {
		Admin admin = (Admin) getSession().get(Admin.class, uid);
		getSession().delete(admin);
	}
}
